#include <bits/stdc++.h>
using namespace std;
const int N = 1.5e5 + 7;
int e[N], w[N], ne[N * 2], h[N], idx;
int d[N];
bool vis[N];
int n, m;
typedef pair<int, int> pi;
priority_queue<pi, vector<pi>, greater<pi>> q;
void add(int x, int y, int z) {
  e[idx] = y, ne[idx] = h[x], w[idx] = z, h[x] = idx++;
}
int main() {
  memset(d, 0x3f, sizeof d);
  memset(h, -1, sizeof h);
  cin >> n >> m;
  while (m--) {
    int x, y, z;
    cin >> x >> y >> z;
    add(x, y, z);
  }
  d[1] = 0;
  q.push({0, 1});
  while (q.size()) {
    auto [dist, u] = q.top();
    q.pop();
    if (vis[u]) continue;
    vis[u] = true;
    for (int i = h[u]; i != -1; i = ne[i]) {
      int v = e[i];
      d[v] = min(d[v], d[u] + w[i]);
      q.push({d[v], v});
    }
  }
  cout << (d[n] == 0x3f3f3f3f ? -1 : d[n]) << '\n';
}
